package
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.geom.Vector3D;

	[SWF(width = "800", height = "600", backgroundColor = "0x66ccff", frameRate="60")]
	public class RotateAndPosition extends Sprite
	{

		private var holder:Sprite;
		private var treeArr:Array = [];
		private var radius:Number = 200;
		private var numTrees:int = 10;
		
		public function RotateAndPosition()
		{
			if(!stage)
			{
				addEventListener(Event.ADDED_TO_STAGE,inits);
			}else
				inits(null);
			
		}
		
		protected function inits(event:Event):void
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			root.transform.perspectiveProjection.fieldOfView = 100;
			
			holder = new Sprite();
			holder.x = stage.stageWidth/2;
			holder.y = stage.stageHeight/2;
			
			addChild(holder);
			
			for (var j:int = 0; j < 3; j++) 
			{
				for (var i:int = 0; i < numTrees; i++) 
				{
					var angle:Number = Math.PI*2/numTrees*i;
					var tree:Tree = new Tree();
					tree.x = Math.cos(angle)*radius;
					tree.z = Math.sin(angle)*radius;
					tree.y = 200+200*j
					tree.rotationY = -360/numTrees*i+90;
					treeArr.push(tree);
				}
			}
			
			
			
			//sortTrees();
			addEventListener(Event.ENTER_FRAME,onEnterFrame);
		}
		
		protected function onEnterFrame(event:Event):void
		{
			holder.rotationY-=(stage.stageWidth/2-mouseX)*.01
			holder.y=-(stage.stageHeight-500)*mouseY/stage.stageHeight;
			sortTrees();
		}
		
		private function sortTrees():void
		{
			treeArr.sort(depthSort);
			for (var i:int=0; i<treeArr.length; i++) 
			{
				holder.addChildAt(treeArr[i] as Tree,i);
			}
		}
		
		private function depthSort(objA:DisplayObject,objB:DisplayObject):int
		{
			var posA:Vector3D = objA.transform.matrix3D.position;
			posA = holder.transform.matrix3D.deltaTransformVector(posA);
			var posB:Vector3D = objB.transform.matrix3D.position;
			posB = holder.transform.matrix3D.deltaTransformVector(posB);
			return posB.z - posA.z;
		}
	}
}